<?php

namespace IDock\Insurance\MACN\Request;

use IDock\Http\Request;
use IDock\Http\RequestMethod;
use IDock\Http\Response;
use IDock\Insurance\MACN\Response\PolicyPaymentResponse;
use IDock\Visitor\PolicyPaymentVisitor;

class PolicyPaymentRequest extends AllMACNRequest
{
    //protected $code = 'V02';
    protected $route = 'vchl-channel/upay/upay.htm';

    protected $method = RequestMethod::GET;

    protected $response = PolicyPaymentResponse::class;

    protected $logTip = '支付';

    public $payGateway = '';

    public function loadConfig(array $config): Request
    {
        $this->gateway = $config['gateway'] ?? '';

        $this->logsDir = $config['logsDir'] ?? '';

        $this->timeout = $config['timeout'] ?? '';

        $this->proxy = $config['proxy'];

        $this->payGateway = $config['WAPPayUrl'] ?? '';

        return  $this;
    }

    /**
     * @var PolicyPaymentVisitor $visitor
     */
    protected $visitor;

    public function request(Request $request,Response $multiplexResponse = null): Response
    {
        return parent::payRequest($request);
    }

    /**
     * 生成支付链接
     * @return string
     */
    public function getPayUrl(): string
    {
        if (!$this->payGateway) {
            $payGateway = parse_url($this->gateway);

            $host = $payGateway['host'];
            $url = 'http://'.$host . '/' . $this->route;
            return $url . '?' . http_build_query($this->generate());

        } else {
            return $this->payGateway . '?' . http_build_query($this->generate());

        }
    }

    public function generate(): array
    {
        $param = [
            'CConfirmNo' => $this->visitor->ciInquiryNo,
            'BConfirmNo' => $this->visitor->biInquiryNo,
        ];

        foreach ($param as $k => $v) {
            if (!$v) {
                unset($param[$k]);
            }
        }

        return $param;
    }
}
